/*		<one line to give the program's name and a brief idea of what it does.>
* Copyright (C) <2025>  <zhen>
* 
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

#ifndef X_CANMSG_H
#define X_CANMSG_H

#include <pthread.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "Xlist.h"
#include "Xstate.h"

#define mail_depth 3 // 收发邮箱的深度，即最大可以缓存多少个CAN帧 最大不能超过32

typedef struct CANmsg
{
    struct timeval tv;
    uint32_t ID;
    uint8_t DLC;
    uint8_t IDE;      // 区分标准帧还是扩展帧，0表示标准帧，1表示扩展帧
    uint8_t RTR;      // 0表示数据帧，1表示远程帧
    uint8_t FDF;      // 区分CAN帧还是CANfd，0为CAN，1为CANfd
    uint8_t Data[64]; // 兼容CANFD 最大64字节数据
} canMsg_t;

struct filter{
    uint32_t ID[2];
    uint32_t mask[2];
};


struct canMsgMail
{
    struct X_list list;
    pthread_spinlock_t spin;
    struct filter filter;   // CAN 接收过滤器，
    int head;
    int tail;
    canMsg_t msgs[mail_depth];
};

uint8_t dlc2len(uint8_t dlc);
uint8_t len2dlc(uint8_t len);
// 输出CAN报文
void dumpCanMsg(FILE *fp,canMsg_t *msg);
// 初始化邮箱
struct canMsgMail *createCanMsgMail(void);
// 释放邮箱
void destroyCanMsgMail(struct canMsgMail *mail);
// 发送
X_s sendCanMsg(struct canMsgMail *mail, canMsg_t *msg);
// 接收
X_s rescvCanMsg(struct canMsgMail *mail, canMsg_t *msg, uint32_t timeout);


#endif // X_CANMSG_H
